package com.jmectf.jgn;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.captiveimagination.jgn.JGN;
import com.captiveimagination.jgn.clientserver.JGNServer;
import com.captiveimagination.jgn.synchronization.SynchronizationManager;
import com.captiveimagination.jgn.synchronization.message.SynchronizeCreateMessage;
import com.jme.scene.Node;
import com.jmectf.game.state.BattleState;
import com.jmectf.game.vehicle.Vehicle;
import com.jmectf.jgn.controller.JMEGraphicalController;
import com.jmex.game.StandardGame;
import com.jmex.game.state.GameStateManager;

public class BattleServer extends BattleSync {

	StandardGame game;
	BattleState gameState;

	public BattleServer() throws SecurityException, NoSuchFieldException, IOException, IllegalArgumentException, IllegalAccessException {
		new Thread(new Runnable() {
			public void run() {
				game = new StandardGame("jmectftest");
				game.start();
				gameState = new BattleState(game);
				GameStateManager.getInstance().attachChild(gameState);
				gameState.setActive(true);
			}
		}).run();
		InetSocketAddress serverReliable = new InetSocketAddress(InetAddress.getLocalHost(), 4242);
		InetSocketAddress serverFast = new InetSocketAddress(InetAddress.getLocalHost(), 4243);
		JGNServer server = new JGNServer(serverReliable, serverFast);
		server.setConnectionLinking(true);
		JMEGraphicalController controller = new JMEGraphicalController();
		SynchronizationManager serverSyncManager = new SynchronizationManager(server, controller);
		serverSyncManager.addSyncObjectManager(this);
		JGN.createThread(server).start();
		JGN.createThread(serverSyncManager).start();
		Field field = BattleState.class.getDeclaredField("player");
		field.setAccessible(true);
		Vehicle vehicle = null;
		System.out.println(gameState);
		while ((vehicle = (Vehicle)field.get(gameState)) == null) {
			try {
				Thread.sleep(100);
			} catch(Exception exc) {
				exc.printStackTrace();
			}
		}
		Node scene = gameState.getRootNode();
		setScene(scene);
		serverSyncManager.register(vehicle, new SynchronizeCreateMessage(), 50);
	}

	public static void main(String[] args) {
		try {
			new BattleServer();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
